#!/usr/bin/env python
#-*- coding:utf8 -*-
"""
Function attributes:
* load: boolean. Optional. If False the function will not load.
* name: string. Optional.
* priority: string. Optional. Three values are available: "high", "medium" or "low",
  default value: "medium".
* thread: boolean. Optional. If True, function will work by starting a thread.
* rule: string or regexp object. Required.
* aliases: list of string or regexp objects. Optional.
* fullmsg: boolean. Optional. If True, pattern is searched on whole message, else
  pattern is a command, the message must begin with a sign.

* access
* evttypes: must be tuple
* skip_sentinel: skip _sentinel instance
* limit
* channels
* url
* showas
"""
import re
from util.pywikilib import Site, Page, WikiLink
from util.functions import join_list
from util import sitematrix
from core.optimizers import fmt, File
field = "maintain"

def m_contest(bot, evt, cmd):
	data = net.pageWiki(u"Viquipèdia:Viquiconcurs")
	m=re.search("(?us)=== Edicions en curs ===.*edició (\d*)\|.*=== Edicions realitzades ===",data)
	if m:
		bot.reply(evt, "http://ca.wikipedia.org/wiki/Viquip%C3%A8dia:Viquiconcurs/edici%C3%B3_%s" % m.group(1))
	else:
		bot.reply(evt, "http://ca.wikipedia.org/wiki/Viquip%C3%A8dia:Viquiconcurs")
m_contest.rule = re.compile(ur"(viqui)?concurs")

def m_maintainance(bot, evt, cmd):
	epotime=int(time.time())-(86400*31)
	bot.reply(evt, "http://ca.wikipedia.org/wiki/Categoria:Viquip%C3%A8dia:Manteniment")
m_maintainance.rule = "maint"

def m_delete(bot, evt, cmd):
	bot.reply(evt, "http://ca.wikipedia.org/wiki/Categoria:Viquip%C3%A8dia:Elements_a_destruir")
m_delete.rule = "bor|esb(orra)?|dest"

def m_requests(bot, evt, cmd):
	bot.reply(evt, "http://ca.wikipedia.org/wiki/Viquip%C3%A8dia:Esborrar_p%C3%A0gines/Propostes")
m_requests.rule = "requests"
m_requests.chanlang = {"ca": "propostes"}

def m_current_vandalism(bot, evt, cmd):
	bot.reply(evt, "http://ca.wikipedia.org/wiki/Viquip%C3%A8dia:Observatori_del_vandalisme")
m_current_vandalism.rule = ["vec","odv"]

def m_vandalism_watch(bot, evt, cmd):
	usr = trurl(args.strip().split(" ")[0])
	if usr=="%21": usr= ""
	links = (
		"http://ca.wikipedia.org/wiki/Viquip%C3%A8dia:Observatori_del_vandalisme/Avisos_autom%C3%A0tics#footer",
		u"http://ca.wikipedia.org/wiki/Special:Contributions/%s" % usr
	)
	if not usr: links=[links[0]]
	for link in links:
		bot.reply(evt, link)
m_vandalism_watch.rule = ["vnd", "vand"]

def m_stats(bot, evt, cmd):
	elimina_inactius()
	msg=estadistiques()
	bot.pubmsg(msg.encode("utf-8"))
m_stats.rule = "s"

def m_links(self, origin, args):
	cmd = args.match.group(1)
	params = args.match.group(2)
	reply=""
	if cmd in ["b", "block"]:
		usr=args.match.group(2)
		reply=u"http://es.wikipedia.org/wiki/Special:Blockip/"+qurl(usr)
	elif cmd in  ["cb", "bc"]:
		usr=args.match.group(2)
		url=u"http://es.wikipedia.org/wiki/Special:$sp$/%s"%qurl(usr)
		reply=[]
		for l in cmd:
			if l == "c":
				reply.append(url.replace("$sp$","Contributions"))
			else:
				reply.append(url.replace("$sp$","BlockIP"))
		self.msglines(origin.target, reply)
		reply=""
	elif cmd.startswith("mant"):
		epotime=int(time.time())-(86400*31)
		reply = [
			"http://es.wikipedia.org/wiki/Categor%C3%ADa:Wikipedia:Mantenimiento",
			u"http://es.wikipedia.org/wiki/Categor%%C3%%ADa:Wikipedia:Mantenimiento:%d_de_%s" %
				(
					int(time.strftime("%d",time.localtime(epotime))),
					i_mes[int(time.strftime("%m",time.localtime(epotime)))]
				)
		]
		self.msglines(origin.target, reply)
		reply=""
	elif cmd.startswith("dest") or cmd.startswith("bor"):
		reply="http://es.wikipedia.org/wiki/Categor%C3%ADa:Wikipedia:Borrar%20%28definitivo%29"
	elif cmd.startswith("vec"):
		reply="http://es.wikipedia.org/wiki/Wikipedia:Vandalismo_en_curso"
	if reply:
		self.msg(origin.target, reply)
m_links.rule = re.compile(r"(?i)^$trigger(mant.*|dest.*|bor.*|vec.*|bc|cb|b|block|a[bd]|cad)(?: (.*))?$")
#links.showas =["bc|cb", "b(lock)", "mant*", "dest*", "bor*", "vec*"]

def m_depth(bot, evt, cmd):
	site = Site("ca")
	page = Page(site, "Usuari:Lohen11/Depth").content()
	regexp = re.compile("\|-----\s+\| (?P<data>[\d/]+?) \|\| (?P<arts>[^ ]+) \|\| (?P<diffarts>[^ ]+) \|\| "
						"(?P<total>[^ ]+) \|\| (?P<diftotal>[^ ]+) \|\| (?P<edicions>[^ ]+) \|\| "
						"(?P<diffeds>[^ ]+) \|\| (?P<edsarts>[^ ]+) \|\| (?P<edsnoarts>[^ ]+) \|\| "
						"(?P<arttot>[^ ]+) \|\| (?P<depthaccu>[^ ]+) \|\| (?P<depthdia>[^ ]+)", re.S | re.M)
	items = regexp.finditer(page)
	d = []
	for item in items:
		d.append((item.group("data"), item.group("depthdia")))
	t = len(d)
	d = d[-3:]
	msg = "total registres: %i | darrers: %s: %s | %s: %s | %s: %s | http://ca.wikipedia.org/wiki/Usuari:Lohen11/Depth#footer" % (
		t, d[0][0], d[0][1], d[1][0], d[1][1], d[2][0], d[2][1]
	)
	bot.reply(evt, msg)
m_depth.rule = "depth"
m_depth.wherelang = "ca"
